package cn.y.operation.framework.utils.dev;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

    private final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    @Retryable(value = {RestClientException.class, Exception.class}, maxAttempts = 3,
            backoff = @Backoff(delay = 5000L, multiplier = 2))
    public static String RetryableHttpPost(String url, Map<String, String> params) {
        // System.out.println("RetryableHttpPost!!!!!!!!!!!!!!!!!!!!!!!");
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            map.add(entry.getKey(), entry.getValue());
        }
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return exchange.getBody();
    }

    public static String doHttpPost(String url, Map<String, String> params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            map.add(entry.getKey(), entry.getValue());
        }
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return exchange.getBody();
    }

    /**
     * RestTemplate 发送  HTTP GET请求
     */
    public static String doHttpGet(String URL, Map<String, Object> params) {
        RestTemplate restTemplate = new RestTemplate();
        StringBuilder andParams = new StringBuilder();
        for (String key : params.keySet()) {
            if (andParams.length() == 0) {
                andParams.append("?");
            } else {
                andParams.append("&");
            }
            try {
                String value = params.get(key).toString();
                if (!StringUtils.isEmpty(value)) {
                    andParams.append(key).append("=").append(URLEncoder.encode(value, StandardCharsets.UTF_8.toString()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String urlAndParams = URL + andParams;
        String response = restTemplate.getForObject(urlAndParams, String.class);
        System.out.println(response);
        return response;
    }

    @Recover
    public void HttpRecovery(Exception e) {
        logger.warn("重试http请求依旧失败了！");
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        Map<String, String> map = new HashMap<>();
        map.put("qwe", "qwe");
        Map<String, Object> paramsPush = new HashMap<>(2);
        paramsPush.put("msg", JSONArray.toJSONString(map));
        paramsPush.put("deviceKey", "123SSSSSAHCJ");
        System.out.println(doHttpGet("http://127.0.0.1:6060/event/events2", paramsPush));
    }
}
